#include <boost/asio.hpp>
//#include <boost/bind.hpp>
#include <memory>
#include <iostream>
#include <string>
#include <functional>
#include <ctime>

using boost::asio::ip::tcp;

std::string make_daytime_string() {
	using namespace std;
	auto now = time(nullptr);
	return ctime(&now);
}
//异步，需要存储每一个连接相关信息
class tcp_connection : public std::enable_shared_from_this<tcp_connection> {
	//需要把自己包装成一个智能指针
public:
	//typedef boost::shared_ptr<tcp_connection> pointer;
	using pointer = std::shared_ptr<tcp_connection>;
	//工厂类
	static pointer create(boost::asio::io_service &io_service) {
		//std::make_shared会调用构造函数，此处构造private
		return pointer(new tcp_connection(io_service));
		//return std::make_shared<tcp_connection>(io_service);
		//第一种，内存分配两次，调用两次new，
		//make_shared使用new一次
	}
	tcp::socket &socket() {return socket_;}
	void start() {
		message_ = make_daytime_string();
		auto self = shared_from_this();
		boost::asio::async_write(
			socket_, boost::asio::buffer(message_),
			[self = std::move(self)](auto error, auto bytes_transferred){
				self->handle_write(error, bytes_transferred);
			});//[值的拷贝/引用] &self不行，会失效，使用值，多一次拷贝
		//往socket里面写，写一个buffer，buffer来源于message_
		//不管写成功没，做一个回调
		//bind(::T::handle, this, ...)//类成员， 谁调用， 调用的参数
		//boost::asio::async_write(
			//socket_, boost::asio::buffer(message_),
			//boost::bind(&tcp_connection::handle_write, 
			//			shared_from_this(),
			//			boost::asio::placeholders::error,
			//			boost::asio::placeholders::bytes_tranforred));
	}


private:
	tcp_connection(boost::asio::io_service &io_service) 
		: socket_(io_service) {}
	void handle_write(const boost::system::error_code &, 
		size_t /*bytes_transferred*/) {}
	tcp::socket socket_;//接口与网络底层通过asio
	std::string message_;
};

class tcp_server {
public:
	tcp_server(boost::asio::io_service &io_service) 
		: acceptor_(io_service, tcp::endpoint(tcp::v4(), 13)) {
		start_accept();	
	}
private:
	void start_accept() {
		//tcp_connection::pointer 生成新连接
		auto new_connection = 
		tcp_connection::create(acceptor_.get_io_service());
		acceptor_.async_accept( new_connection->socket(),
								[this, new_connection](auto error) {
								this->handle_accept(new_connection, error);
								});
		//acceptor_.async_accept( new_connection->socket(),
		//						boost::bind(&tcp_server::handle_accept, this
		//									new_connection,
		//									boost::asio::placeholders::error));
	}
	void handle_accept( tcp_connection::pointer new_connection,
						const boost::system::error_code &error) {
		//是否连接成功的connection
		if(!error) {
			new_connection->start();
		}
		start_accept();
	}
	tcp::acceptor acceptor_;
};

int main() {
	try{
		boost::asio::io_service io_service;
		tcp_server server(io_service);
		io_service.run();
	}catch(std::exception &e){
		std::cerr << e.what() <<std::endl;
	}
	return 0;
}
